package org.flycloud.web.sso.client;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.flycloud.web.sso.common.SessionCache;
import org.flycloud.web.sso.common.SystemSession;
import org.flycloud.web.sso.common.UserSession;

public class MyAuthorizingRealm extends AuthorizingRealm {

	private SessionCache sessions;

	public MyAuthorizingRealm() {
		super();
		setName("myRealm");
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		UserSession user = (UserSession) getAvailablePrincipal(principals);
		if (user != null) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

			for (String permission : user.getPermissions()) {
				info.addStringPermission(permission);
			}

			for (String role : user.getRoles()) {
				info.addRole(role);
			}

			return info;
		} else {
			return null;
		}
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		UserSession user = sessions.getToken(token.getUsername());
		if (user != null) {
			return new SimpleAuthenticationInfo(user, SystemSession.CREDENTIALS,
					ByteSource.Util.bytes(user.getUserName()), getName());
		} else {
			System.out.println(token.getUsername() + " session not exist!");
		}
		return null;
	}

	public void setCache(SessionCache s) {
		this.sessions = s;
	}

}